//
//  CZComposeView.swift
//  weibo
//
//  Created by 丁蒙 on 16/7/3.
//  Copyright © 2016年 丁蒙. All rights reserved.
//

import UIKit

class CZComposeView: UICollectionView {
    //重用标识
    private let pictureViewCellId: String = "pictureViewCellId"
    
    //存放图片的数组
    var imageList: [UIImage] = [UIImage]()
    
    //跳转到相册的闭包
    var composeViewClosure:(()->())?
    
    let itemMargin: CGFloat = 5
    
    // MARK: - 共外界调用 添加图片
    func addImage(image: UIImage) {
        imageList.insert(image, atIndex: 0)
        
        if imageList.count > 9 {
            imageList.removeLast()
        }
        //刷新数据
        reloadData()
    }
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        super.init(frame: frame, collectionViewLayout: UICollectionViewFlowLayout())
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: - 设置视图
    private func setupUI() {
        self.backgroundColor = UIColor.whiteColor()
        dataSource = self
        delegate = self
        //注册
        registerClass(CZComposeCell.self, forCellWithReuseIdentifier: pictureViewCellId)
        let layout = collectionViewLayout as! UICollectionViewFlowLayout
        
        let itemSizeHW = (SCREENW - 20 - itemMargin * 2) / 3
        
        layout.itemSize = CGSizeMake(itemSizeHW, itemSizeHW)
        
        layout.minimumLineSpacing = itemMargin
        
        layout.minimumInteritemSpacing = itemMargin
    }
    
}
// MARK: - UICollectionViewDataSource
extension CZComposeView: UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        let count = imageList.count
        
        if count == 0 || count == 9 {
            return count
        } else {
            
            return imageList.count + 1
            
        }
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureViewCellId, forIndexPath: indexPath) as! CZComposeCell
        
        if imageList.count == indexPath.item {
            cell.image = nil
        } else {
            cell.image = imageList[indexPath.item]
        }
        //执行闭包
        cell.composeDeleteClosure = {
            self.imageList.removeAtIndex(indexPath.item)
            if self.imageList.count == 0 {
                self.hidden = true
            }
            self.reloadData()
        }
        return cell
    }
    //点击选中cell
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        if imageList.count == indexPath.item {
    
            composeViewClosure?()
        }
    }
}

// MARK: - 自定义UICollectionViewCell
class CZComposeCell: UICollectionViewCell {
    //删除按钮 闭包
    var composeDeleteClosure:(()->())?
    //cell的背景图
    var image: UIImage? {
        didSet {
            if image == nil {
                bgImageView.image = UIImage(named: "compose_pic_add")
                bgImageView.highlightedImage = UIImage(named: "compose_pic_add_highlighted")
                deleteButton.hidden = true
            } else {
                bgImageView.image = image
                bgImageView.highlightedImage = nil
                deleteButton.hidden = false
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setupUI() {
    
        addSubview(bgImageView)
        addSubview(deleteButton)
        
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        deleteButton.snp_makeConstraints { (make) in
            make.top.right.equalTo(self)
        }
    }
    // MARK: - 监听删除按钮点击
    @objc private func deleteButtonClick() {
        composeDeleteClosure?()
    }
    //懒加载控件
    private lazy var bgImageView: UIImageView = UIImageView()
    //取消按钮
    private lazy var deleteButton: UIButton = {
       let btn = UIButton()
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "compose_photo_close"), forState: UIControlState.Highlighted)
        ///添加点击事件
        btn.addTarget(self, action: #selector(CZComposeCell.deleteButtonClick), forControlEvents: UIControlEvents.TouchUpInside)
        return btn
    }()
}
